package com.base.service.client;

import java.util.*;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;

import tool.TimeTool;
import tool.encrypt.IdentifyTool;

import com.base.bean.*;
import com.base.dao.*;

/**
 * 客户拥有者服务类功能： 1）获取客户当前拥有者状态 2）改变拥有人
 * 
 * 说明： 拥有者状态1:normal -1:leave -2:expire 过期的判定依据是，当前客户最近一次行动已经超过100天
 * 
 * @author chz
 * 
 */
public class ClientOwnerService {

	private static int EXPIRE_DAYS = 100;
	private ActivityDao activityDao;
	private ClientBaseDao clientBaseDao;
	private UserDao userDao;

	// 单例模式 start
	private volatile static ClientOwnerService instance = null;

	private ClientOwnerService() {
		this.activityDao = (ActivityDao) _BaseDao.ac.getBean("ActivityDao");
		this.clientBaseDao = (ClientBaseDao) _BaseDao.ac
				.getBean("ClientBaseDao");
		this.userDao = (UserDao) _BaseDao.ac.getBean("UserDao");
	}

	public static ClientOwnerService getInstance() {
		if (instance == null) {
			synchronized (ClientOwnerService.class) {// 1
				if (instance == null) {// 2
					instance = new ClientOwnerService();// 3
				}
			}
		}
		return instance;
	}

	// 单例模式 end

	/**
	 * 获取客户所有者状态
	 * 
	 * @param expireDays
	 *            过期天数上限
	 * @param cid
	 * @param uid
	 * @return 0:正常状态 1:拥有人离职 2:拥有人长期未跟踪实效
	 * 
	 * flag:1：第一步  2:第二步（结束）
	 * 
	 *         可以这么判断：>0:success <0:fail
	 */
	public ChangeOwnerFormBean changeOwner(ChangeOwnerFormBean bean,
			int expireDays) {

		ClientBase cb = null;
		Activity actv = null;
		User user = null;
		User owner = null;
		int days = 0;

		Session session = null;
		Transaction tx = null;
		try {
			session = this.activityDao.getSessionFactory().getCurrentSession();
			tx = session.beginTransaction();

			user = (User) session.createCriteria(User.class)
					.add(Restrictions.eq("openid", bean.getOpenId()))
					.uniqueResult();
			
			if(user==null){
				bean.setFlag(-1);
				bean.setResult(false);
				bean.setTip("请重新登录");
				return bean;
			}
			
			

			cb = (ClientBase) session.createCriteria(ClientBase.class)
					.add(Restrictions.eq("cid", bean.getCid())).uniqueResult();

			owner = (User) session.createCriteria(User.class)
					.add(Restrictions.eq("uid", cb.getOwner())).uniqueResult();

			actv = (Activity) session.createCriteria(Activity.class)
					.add(Restrictions.eq("cid", bean.getCid()))
					.addOrder(Order.desc("created")).setMaxResults(1)
					.uniqueResult();
			if (actv != null)
				days = (int) ((new java.util.Date().getTime() - actv
						.getCreated().getTime()) / (1000 * 60 * 60 * 24));
			else
				// 如果没有行动 则以客户创建时间为准
				days = (int) ((new java.util.Date().getTime() - cb.getCreated()
						.getTime()) / (1000 * 60 * 60 * 24));

			if (bean.getState() == 0) { // 仅仅查看客户拥有人状态
				
				if (owner.getState() == 2) {
					bean.setFlag(1);
					bean.setTip("该客户对应销售员已经离职处于解锁状态，是否接收该客户");
					bean.setResult(true);
					bean.setLocked(false);
					
				}else if (days > expireDays) {
					bean.setFlag(1);
					bean.setTip("该客户已经解锁，是否接收该客户");
					bean.setResult(true);
					bean.setLocked(false);	
				}else{
					bean.setFlag(2);
					bean.setTip("该客户目前属于其他销售员，暂时无法创建行动");
					bean.setResult(true);
				}
			} else if (bean.getState() == 1){ // 需要修改拥有者
				bean.setFlag(2);
				if ((owner.getState() == 2) || (days > expireDays)) {

					// 更改所属人
					String hqlUpdate = "";
					int updatedEntities = 0;
					hqlUpdate = "update ClientPhone p set p.owner = :owner where p.cid= :cid";
					// or String hqlUpdate =
					// "update Customer set name = :newName where name = :oldName";
					updatedEntities = session.createQuery(hqlUpdate)
							.setInteger("owner", user.getUid())
							.setInteger("cid", bean.getCid()).executeUpdate();

					hqlUpdate = "update ClientBase  p set p.owner = :owner ,p.modified= :modified  where p.cid= :cid";
					updatedEntities = updatedEntities
							+ session
									.createQuery(hqlUpdate)
									.setInteger("owner", user.getUid())
									.setTimestamp("modified",
											TimeTool.getCurrentTime())
									.setInteger("cid", bean.getCid())
									.executeUpdate();

					hqlUpdate = "update ClientExtend  p set p.owner = :owner where p.cid= :cid";
					updatedEntities = updatedEntities
							+ session.createQuery(hqlUpdate)
									.setInteger("owner", user.getUid())
									.setInteger("cid", bean.getCid())
									.executeUpdate();
					
					
					bean.setLocked(false);
					bean.setTip("您已成功接收该客户");
					bean.setResult(true);
					
				} else {
					bean.setTip("您未能成功接收该客户");
					bean.setResult(false);
					
				}

			}
			tx.commit();
			return bean;
		} catch (Exception e) {
			e.printStackTrace();
			tx.rollback();

		}

		finally {
			if (session.isOpen())
				session.close();
		}
		return bean;

	}

	public static void main(String args[]) {
		ClientOwnerService cs = ClientOwnerService.getInstance();
		// int cid= 15449;
		// int result = cs.getOwnerState(cid, 100);

		Integer cid2 = tool.encrypt.IdentifyTool.deCode("KH_123371", 1);
		System.out.println("cid2:" + cid2);

		// int r = cs.changeOwner(cid2, 1);

		// System.out.println(r);

		// System.out.println("result:"+result);
	}

}
